<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="单据号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder=""
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 280px"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId" >
        <el-select v-model="queryParams.supplierId" @keyup.enter.native="handleQuery" clearable style="width: 280px">
          <el-option v-for="supplier in SupplierList" :key="supplier.id" :value="supplier.id" :label="supplier.name" >{{supplier.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作人" prop="createById" >
        <el-select v-model="queryParams.createById" style="width: 280px" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.id" :label="user.userName">{{user.userName}}</el-option>
        </el-select>
      </el-form-item><br/>
      <el-form-item label="操作时间" prop="createTime">
        <el-date-picker clearable
                        v-model="queryParams.createMinTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        style="width: 130px">
        </el-date-picker>
        至
        <el-date-picker clearable
                        v-model="queryParams.createMaxTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        style="width: 130px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核人" prop="approveBy" >
        <el-select v-model="queryParams.approveBy" style="width: 280px" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user1 in UserList" :key="user1.userName" :value="user1.userName" :label="user1.userName">{{user1.userName}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" prop="approveTime">
        <el-date-picker clearable
                        v-model="queryParams.approveMinTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        style="width: 130px"
        >
        </el-date-picker>
        至
        <el-date-picker clearable
                        v-model="queryParams.approveMaxTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        style="width: 130px"
        >
        </el-date-picker>
      </el-form-item><br/>
      <el-form-item label="状态" prop="status" >
        <el-select v-model="queryParams.status" style="width: 280px" @keyup.enter.native="handleQuery" clearable>
          <el-option value="0" label="待审核">待审核</el-option>
          <el-option value="3" label="审核通过">审核通过</el-option>
          <el-option value="6" label="审核拒绝">审核拒绝</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="结算状态" prop="settleStatus" >
        <el-select v-model="queryParams.settleStatus" style="width: 280px" @keyup.enter.native="handleQuery" clearable>
          <el-option value="0" label="未结算">未结算</el-option>
          <el-option value="1" label="结算中">结算中</el-option>
          <el-option value="2" label="已结算">已结算</el-option>
          <el-option value="6" label="无需结算">无需结算</el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 30px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:SettleCheckSheet:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:SettleCheckSheet:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SettleCheckSheetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据号" align="center" prop="code"  show-overflow-tooltip  width="200"/>
      <el-table-column label="供应商编号" align="center" prop="bcode"  width="190"/>
      <el-table-column label="供应商名称" align="center" prop="name"  width="100px"/>
      <el-table-column label="单据金额" align="center" prop="totalAmount"  width="120px">
        <template slot-scope="scope">
          {{ Number(scope.row.totalAmount).toLocaleString('en-US') }}
        </template>
      </el-table-column>
      <el-table-column label="应付总金额" align="center" prop="totalPayAmount"  width="120px">
        <template slot-scope="scope">
          {{ Number(scope.row.totalPayAmount).toLocaleString('en-US') }}
        </template>
      </el-table-column>
      <el-table-column label="已付款金额" align="center" prop="totalPayedAmount"  width="120px">
        <template slot-scope="scope">
          {{ Number(scope.row.totalPayedAmount).toLocaleString('en-US') }}
        </template>
      </el-table-column>
<!--      <el-table-column label="已优惠金额" align="center" prop="totalDiscountAmount"  width="120px">-->
<!--        <template slot-scope="scope">-->
<!--          {{ Number(scope.row.totalDiscountAmount).toLocaleString('en-US') }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="未付款金额" align="center"  width="120px">
        <template slot-scope="scope">
          <span>{{  Number(scope.row.totalPayAmount - scope.row.totalPayedAmount).toLocaleString('en-US') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="createBy" width="120px" />
      <el-table-column label="状态" align="left" prop="status" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">待审核</span>
          <span v-if="scope.row.status == 3">审核通过</span>
          <span v-if="scope.row.status == 6">审核拒绝</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="approveBy"  width="120px"/>
      <el-table-column label="结算状态" align="center" prop="settleStatus" >
        <template slot-scope="scope">
          <span v-if="scope.row.settleStatus == 0">未结算</span>
          <span v-if="scope.row.settleStatus == 1">结算中</span>
          <span v-if="scope.row.settleStatus == 2">已结算</span>
          <span v-if="scope.row.settleStatus == 6">无需结算</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="description" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width"  fixed="right" width="200px">
        <template slot-scope="scope">
          <el-button
            size="medium"
            type="text"
            @click="getShow(scope.row)"
            v-hasPermi="['system:SettleCheckSheet:edit']"
          >查看</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status !=3"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:SettleCheckSheet:edit']"
          >修改</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status !=3"
            @click="statusUpdate(scope.row)"
          >审核</el-button>
          <el-button
            style="color: red"
            size="medium"
            type="text"
            v-if="scope.row.status !=3"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:SettleCheckSheet:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看按钮 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <div style="display: inline-block;width: 300px;">
          <p>供应商：{{ this.settleCheckSheetShow.name }}</p>
        </div>
        <div style="display: inline-block;width: 430px;">
          审核时间：
          <el-date-picker clearable disabled
              v-model="this.settleCheckSheetShow.startDate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 154px"
          >
          </el-date-picker>
          至
          <el-date-picker clearable disabled
              v-model="this.settleCheckSheetShow.endDate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 154px"
          >
          </el-date-picker>
        </div>
        <br/>
        <div style="display: inline-block;width: 300px;"><p>状态：<span :style="{color: statusColor}">{{ this.settleCheckSheetShow.status==0 ? '待审核' : (this.settleCheckSheetShow.status==3 ? '审核通过' : '审核拒绝') }}</span></p></div>
        <div style="display: inline-block;width: 350px;" v-if="this.settleCheckSheetShow.refuseReason != null && this.settleCheckSheetShow.refuseReason != ''">
          <p>
            拒绝原因：
            <input type="text" style="background-color: #FFFFFF;height: 30px;width: 220px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid;" disabled v-model="this.settleCheckSheetShow.refuseReason" >
          </p>
        </div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>操作人：{{ this.settleCheckSheetShow.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>操作时间：{{ this.settleCheckSheetShow.createTime }}</p></div><br/>
        <div style="display: inline-block;width: 300px;" v-if="this.settleCheckSheetShow.approveBy != null"><p>审核人：{{ this.settleCheckSheetShow.approveBy }}</p></div>
        <div style="display: inline-block;width: 300px;"  v-if="this.settleCheckSheetShow.approveTime != null"><p>审核时间：{{ this.settleCheckSheetShow.approveTime }}</p></div>
      </div>

      <div style="border: 1px gainsboro solid;">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-table :data="this.settleCheckSheetShow.settleCheckSheetDetailList" :row-class-name="rowTblPurchaseOrderDetailIndex" @selection-change="handleTblPurchaseOrderDetailSelectionChange" ref="tblPurchaseOrderDetail">
            <el-table-column label="单据号" prop="bizCode" width="170"  />
            <el-table-column label="单据类型" prop="bizType" width="170">
              <template slot-scope="scope">
                {{scope.row.bizType==1 ? '应收款' : '应付款'}}
              </template>
            </el-table-column>
            <el-table-column label="审核时间" prop="approveTime" width="170" />
            <el-table-column label="单据金额" prop="totalAmount" width="130" >
              <template slot-scope="scope">
                {{ Number(scope.row.totalAmount).toLocaleString('en-US') }}
              </template>
            </el-table-column>
            <el-table-column label="应收金额" prop="payAmount" width="130" >
              <template slot-scope="scope">
                {{ Number(scope.row.payAmount).toLocaleString('en-US') }}
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="description" width="170"/>
          </el-table>
        </el-form>
      </div>

      <div style="border: 1px gainsboro solid;padding: 10px">
        <h3 style="margin:0 0 15px 10px;font-weight: bolder;">合计</h3>
        <div style="display: inline-block;margin-left:40px">
          单据总金额：<input type="text" v-model="Number(this.settleCheckSheetShow.totalAmount).toLocaleString('en-US')" style="background-color: #FFFFFF;height: 30px;width: 140px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid;text-align: right" disabled>
        </div>
        <div style="display: inline-block;margin-left:40px">
          应付总金额：<input type="text" v-model="Number(this.settleCheckSheetShow.totalAmount).toLocaleString('en-US')" style="background-color: #FFFFFF;height: 30px;width: 140px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid;text-align: right" disabled>
        </div>
      </div>
      <div style="border: 1px gainsboro solid;padding: 10px;text-align: right">
        <label >备注： </label>
        <textarea style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid" v-model="this.settleCheckSheetShow.description" disabled/>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <!--        <el-button type="primary" @click="submitForm()" v-if="this.title == '查看'">打 印</el-button>-->
        <el-button type="success" style="background: #1890ff;border: 1px #1890ff solid" @click="submitForm(3)" v-if="this.title == '审核供应商预付款'">审核通过</el-button>
        <el-button type="danger" @click="submitForm(6)" v-if="this.title == '审核供应商预付款'&&this.form.status!=6">审核拒绝</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 拒绝原因 -->
    <el-dialog :title="title" :visible.sync="refuseOpen" width="600px" append-to-body>
      <el-form ref="refuseForm" :model="refuseForm" :rules="refuseRules" label-width="80px">
        <el-form-item label="拒绝原因" prop="reason">
          <el-input type="textarea" v-model="refuseForm.reason" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="refuseSubmit">确 定</el-button>
        <el-button @click="cancelOne">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSettleCheckSheet, getSettleCheckSheet, delSettleCheckSheet, addSettleCheckSheet, updateSettleCheckSheet } from "@/api/system/SettleCheckSheet";
import { listUser} from "@/api/system/user";
import {listSupplier} from "@/api/system/Supplier";
import { getInfo } from '@/api/login'

//日期转换
function formatDateToBackend(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
export default {
  name: "SettleCheckSheet",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSettleCheckSheetDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      statusColor:"rgb(100, 100, 100)",
      // 供应商对账单表格数据
      SettleCheckSheetList: [],

      settleCheckSheetShow:[],
      // 供应商对账单明细表格数据
      settleCheckSheetDetailList: [],
      //用户列表
      UserList: [],
      user:[],
      //拒绝原因
      refuseOpen:false,
      //拒绝原因
      refuseForm: {
        reason: null
      },
      refuseRules: {
        reason: [
          { required: true, message: "拒绝原因不能为空", trigger: "blur" }
        ]
      },
      // 供应商列表
      SupplierList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        supplierId: null,
        createById: null,
        createMinTime: null,
        createMaxTime: null,
        approveBy: null,
        approveMinTime: null,
        approveMaxTime: null,
        status: null,
        settleStatus: null,
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList();
    this.getUserList();
    this.getSupplierList();
    //获取登录进来的用户信息
    this.getUser();
  },
  methods: {
    /** 查询供应商对账单列表 */
    getList() {
      this.loading = true;
      listSettleCheckSheet(this.queryParams).then(response => {
        this.SettleCheckSheetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.UserList = response.rows;
      });
    },
    /** 查询供应商列表 */
    getSupplierList() {
      this.loading = true;
      listSupplier(this.queryParams).then(response => {
        this.SupplierList = response.rows;
      });
    },
    //查询当前登录的用户信息
    getUser() {
      this.loading = true;
      getInfo().then(response => {
        this.user = response.user;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        supplierId: null,
        totalAmount: null,
        totalPayAmount: null,
        totalPayedAmount: null,
        totalDiscountAmount: null,
        startDate: null,
        endDate: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        approveBy: null,
        approveTime: null,
        status: null,
        refuseReason: null,
        settleStatus: null
      };
      this.settleCheckSheetDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.createMinTime = null;
      this.queryParams.createMaxTime = null;
      this.queryParams.approveMinTime=null;
      this.queryParams.approveMaxTime= null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.$router.push({
        path:'/SettleCheckSheet/add',
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.$router.push({
        path:'/SettleCheckSheet/update',
        query:{
          id: id,
        }
      })
    },
    /** 提交按钮 */
    submitForm(status) {
      if (status==6){
        // this.open = false;
        this.refuseOpen=true
      }else {
        this.form.status=status;
        this.form.approveBy=this.user.userName;
        this.form.refuseReason='';
        this.form.approveTime=formatDateToBackend(new Date());
        this.$refs["form"].validate(valid => {
          if (valid) {
            updateSettleCheckSheet(this.form).then(response => {
              if(status==3){
                this.$modal.msgSuccess("审核成功");
              }else {
                this.$modal.msgError("审核拒绝")
              }
              this.open = false;
              this.getList();
            });
          }
        });
      }
    },
    //审批按钮
    statusUpdate(row){
      this.reset();

      const id = row.id || this.ids
      getSettleCheckSheet(id).then(response => {
        this.form = response.data;
        console.log(this.form);
        this.settleCheckSheetShow = response.data;
        this.open=true;
        this.title = "审核供应商预付款";
      });

      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else {
        this.statusColor = "rgb(255, 0, 0)";
      }
    },
    //拒绝原因
    refuseSubmit() {
      this.$refs["refuseForm"].validate(valid => {
        if (valid) {
          this.form.status=6;
          this.form.approveBy=this.user.userName;
          this.form.refuseReason=this.refuseForm.reason
          this.form.approveTime=formatDateToBackend(new Date());
          updateSettleCheckSheet(this.form).then(response => {
            this.$modal.msgError("审批拒绝");
            this.refuseOpen = false;
            this.open = false;
            this.getList();
          });
        }
      });
    },
    cancelOne(){
      this.refuseOpen = false;
      this.refuseForm = {reason:  null}
    },
    /** 查询详情*/
    getShow(row) {
      this.loading = true;
      const id = row.id || this.ids
      getSettleCheckSheet(id).then(response => {
        this.settleCheckSheetShow = response.data;
        this.open=true;
        this.loading = false;
        this.title = "查看";
      });
      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else {
        this.statusColor = "rgb(255, 0, 0)";
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除供应商对账单编号为"' + ids + '"的数据项？').then(function() {
        return delSettleCheckSheet(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/SettleCheckSheet/export', {
        ...this.queryParams
      }, `SettleCheckSheet_${new Date().getTime()}.xlsx`)
    },
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 重新获取数据
      vm.getList();
    });
  }
};
</script>
